import {
  upload,
  imgUrl
} from '../../config/config'
import {
  throttle2,
  debounce
} from "../../utils/util";

import customerApi from '../../utils/customerApi' // 引入api接口管理文件
import websocket from '../../utils/socket'
import api from '../../utils/api'
const app = getApp()
const defaultImg = 'fc06c557-e854-4ba8-a459-863e06f315bf.jpg' // 默认图片
let provincesData = [];
let cityData = [];
Page({
  data: {
    imgUrl,
    type: 'question',
    sender_type: 'customer',
    beforeTime: null,
    toView: '',
    isBot: false,
    talkList: [],
    questionList: [],
    activeIndex: 0,
    isQuestionOpen: false,
    messageText: '',
    loading: false,
    isShow: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    app.globalData.currentPage = 'customerIntelligent' // 全局设置当前页
    this.showLoading()
    this.otherInit();
    this.getAreaProvincesOnce()
  },

  onShow() {
    console.log('onshow customerIntelligent')
    this.setWebsocket();
    this.timer = setTimeout(() => {
      this.setWebsocket();
    }, 2000)
    this.setData({
      isShow: true
    })
    wx.setNavigationBarTitle({
      title: app.globalData.customerChoose.user_data.nickname
    })
  },
  onHide() {
    this.setData({
      isShow: false
    })
  },

  onunload() {
    app.globalData.currentPage = ''
    clearTimeout(this.timer)
  },

  /**
   * @description: 初始化
   */
  init() {
    // 修改title是异步的 会将其他页面的标题也改掉
    this.data.isShow && wx.setNavigationBarTitle({
      title: app.globalData.customerChoose.user_data.nickname
    })
    this.setData({
      isBot: (app.globalData.customerChoose || {}).friend_uid === 'chat_bot', // 是否是机器人
      beforeTime: null,
      talkList: [],
      loading: false
    }, () => {
      this.getList()
    })
  },

  /**
   * @description: 获取省份数据 第一次
   */
  getAreaProvincesOnce() {
    api.areaProvinces({
      data: {},
      success: (res) => {
        if (+res.code === 0) {
          provincesData = res.data
          this.getCityListonce(res.data[0].id)
        }
      },
    });
  },

  /**
   * @description: 获取城市 第一次
   * @param {*} provinceId
   */
  getCityListonce(provinceId) {
    api.areaCities({
      data: {
        provinceId,
      },
      success: (res) => {
        if (+res.code === 0) {
          cityData = res.data
          this.init(true);
        }
      },
    });
  },

  showLoading() {
    wx.showLoading({
      title: '加载中...',
      mask: true,
    });
  },

  otherInit() {
    this.getVaccineCategoryList();
    this.getUserQuestionFullList();
  },

  setWebsocket() {
    websocket({}, (res) => {
      console.log('WebSocket customerIntelligent ===>', res)
      let data = JSON.parse(res)
      if (data.msg && Object.keys(data.msg).length > 0 && app.globalData.currentPage === 'customerIntelligent') {
        this.setData({
          toView: '',
        }, () => {
          this.getList()
        })
      }
    })
  },

  handleimagerr(e) {
    const {
      index
    } = e.currentTarget.dataset
    const {
      talkList
    } = this.data
    talkList[index].message_data.org = defaultImg
    this.setData({
      talkList
    })
  },

  getList() {
    customerApi.conversationReceiveMessage({
      data: {
        conversation_id: app.globalData.customerChoose.conversation_id,
        before: this.data.beforeTime,
        limit: 30,
        update_new_messages_count: true
      },
      success: res => {
        if (res.code * 1 === 0) {
          // 转客服判断
          this.transitionCustomer(res.data)
          // 处理数据
          this.hanndleListData(res.data)
          wx.hideLoading();
        }
      }
    })
  },

  /**
   * @description: 处理列表数据
   */
  hanndleListData(data) {
    if (!data || data.length <= 0) return
    data = data.reverse() // 反转数据
    let newData = []
    let temp = {}
    let result = []
    let toView = ''
    toView = `data_${(data[data.length - 1] || {}).message_id}`
    if (this.data.beforeTime) {
      newData = [...data, ...this.data.talkList]
    } else {
      newData = [...this.data.talkList, ...data]
    }

    // 过滤消息
    newData.map(function (item) {
      if (!temp[item.message_id]) {
        item = {
          ...item,
          viewid: `data_${item.message_id}`
        }
        if (item.type === 'REQUEST_BOT_PRODUCT_LIST' && !item.cityList) {
          item.cityList = [provincesData, cityData];
        }
        result.push(item);
        temp[item.message_id] = true
      }
    })

    this.setData({
      talkList: result,
      loading: false
    })

    this.toViewBydebounce(toView)
  },

  toViewBydebounce: debounce(function (toView) {
    this.setData({
      toView,
    })
  }, 200),

  // 转客服判断
  transitionCustomer(data) {
    for (let i = 0; i < data.length; i++) {
      if (data[i].type === 'INFO' && data[i].action_tag === 'transfer_conversation') {
        customerApi.getTransferConversationInfo({
          data: {
            old_conversation_id: data[i].conversation_id,
            transfer_conversation_id: data[i].action_tag_value,
            message_id: data[i].message_id
          },
          success: tranRes => {
            if (tranRes.code * 1 === 0) {
              app.globalData.customerChoose = tranRes.data
              this.init()
              this.timer = setTimeout(() => {
                this.getList()
              }, 2000)
            }
          }
        })
        break
      }
    }
  },

  onChangeCrmThrottle2: throttle2(function () {
    const customerChoose = app.globalData.customerChoose || {}
    const {
      loading,
      isBot
    } = this.data
    if (loading || !isBot) return
    this.handleLoading(true)
    this.showLoading()
    customerApi.realCrm({
      data: {
        conversation_id: customerChoose.conversation_id,
        uid: customerChoose.uid,
      },
      success: (res) => {
        if (+res.code === 0) {
          this.handleSuccess(true);
        } else {
          this.handleLoading(false)
        }
      },
      fail: () => {
        this.handleLoading(false)
      }
    })
  }, 2000),

  // 转人工客服
  onChangeCrm() {
    this.onChangeCrmThrottle2()
  },

  /**
   * @description: 获取省份数据
   */
  getAreaProvinces(index) {
    api.areaProvinces({
      data: {},
      success: (res) => {
        if (+res.code === 0) {
          const {
            talkList
          } = this.data;
          talkList[index].cityList = [res.data]
          this.setData({
            talkList,
            provincesList: res.data
          }, () => {
            this.getCityList(index, res.data[0].id)
          })
        }
      },
    });
  },

  /**
   * @description: 获取城市
   * @param {*} provinceId
   */
  getCityList(index, provinceId) {
    console.log('index: ', index);
    api.areaCities({
      data: {
        provinceId,
      },
      success: (res) => {
        if (+res.code === 0) {
          const {
            talkList
          } = this.data;
          talkList[index].cityList[1] = res.data
          this.setData({
            talkList,
            cityList: res.data
          });
        }
      },
    });
  },

  /**
   * @description: 获取疫苗类型数据
   */
  getVaccineCategoryList() {
    api.vaccineCategoryList({
      success: (res) => {
        if (+res.code === 0) {
          this.setData({
            categoryList: (res.data.dataList || []).filter(item => item.show).map(item => ({
              id: item.id,
              name: item.name
            }))
          })
        }
      },
    });
  },

  /**
   * @description: 获取所有的问题
   */
  getUserQuestionFullList() {
    const customerChoose = app.globalData.customerChoose || {}
    customerApi.userQuestionFullList({
      data: {
        conversation_id: customerChoose.conversation_id,
        uid: customerChoose.uid,
      },
      success: (res) => {
        if (+res.code === 0) {
          this.setData({
            questionList: res.data
          })
        }
      },
    });
  },

  /**
   * @description: 改变city
   */
  handleCity(e) {
    const {
      id,
      index
    } = e.detail
    this.getCityList(index, id)
  },

  handleMain(e) {
    const {
      column,
      value
    } = e.detail;
    const {
      cityIndex
    } = this.data;
    cityIndex[column] = value
    this.setData({
      cityIndex
    })
  },

  /**
   * @description: 文本输入
   */
  textInput(e) {
    this.setData({
      messageText: e.detail.value
    })
  },

  sendTextBythrottle2: throttle2(function (e) {
    let message_text = ''
    // 如果是智能客服的问题过来 则是string类型, 发送消息过来是object类型
    if (typeof e.detail === 'string') {
      if (!e.detail) return;
      message_text = e.detail
    } else {
      if (!this.data.messageText) return;
      message_text = this.data.messageText
    }
    if (this.data.loading) return
    this.handleLoading(true)
    const customerChoose = app.globalData.customerChoose || {}
    customerApi.conversationSendTextMessage({
      data: {
        friend_uid: customerChoose.friend_uid,
        friend_type: customerChoose.friend_type,
        message: {
          "message_text": message_text
        }
      },
      success: (res) => {
        if (+res.code === 0) {
          this.handleSuccess();
        } else {
          this.handleLoading(false)
        }
      },
      fail: () => {
        this.handleLoading(false)
      }
    })
  }, 2000),

  /**
   * @description: 发送文字
   */
  sendText(e) {
    this.sendTextBythrottle2(e)
  },

  /**
   * @description: 点击退款
   */
  goRefund() {
    this.sendText({
      detail: '联系客服退款'
    })
  },

  /**
   * @description: 成功处理
   * @param {*} loading
   */
  handleSuccess(loading = false) {
    this.setData({
      beforeTime: null,
      messageText: '',
      afterTime: new Date().getTime() - 10 * 1000,
      toView: '',
      loading
    }, () => {
      this.getList()
    })
  },

  /**
   * @description: 失败处理或者初始化处理
   */
  handleLoading(status = false) {
    this.setData({
      loading: status
    })
  },

  onSendQuestionBythrottle2: throttle2(function() {
    const customerChoose = app.globalData.customerChoose || {}
    if (this.data.loading) return
    this.handleLoading(true)
    customerApi.userQuestionList({
      data: {
        conversation_id: customerChoose.conversation_id,
        uid: customerChoose.uid,
      },
      success: (res) => {
        if (+res.code === 0) {
          this.handleSuccess();
        } else {
          this.handleLoading(false)
        }
      },
      fail: () => {
        this.handleLoading(false)
      }
    })
  }, 2000),

  /**
   * @description: 点击猜你想问
   */
  onSendQuestion() {
    this.onSendQuestionBythrottle2()
  },

  onSendProductionBythrottle2: throttle2(function() {
    const customerChoose = app.globalData.customerChoose || {}
    if (this.data.loading) return
    this.handleLoading(true)
    customerApi.userProductList({
      data: {
        conversation_id: customerChoose.conversation_id,
        uid: customerChoose.uid,
      },
      success: (res) => {
        if (+res.code === 0) {
          this.handleSuccess();
        } else {
          this.handleLoading(false)
        }
      },
      fail: () => {
        this.handleLoading(false)
      }
    })
  }, 2000),

  /**
   * @description: 点击推荐商品
   */
  onSendProduction() {
    this.onSendProductionBythrottle2()
  },

  /**
   * @description: 点赞
   */
  submitFeedback(e) {
    const {
      talkList
    } = this.data;
    let i = +e.detail.index || 0
    talkList[i].message_data.message_feedback = e.detail.message_feedback
    this.setData({
      talkList
    })
    customerApi.submitFeedback({
      data: {
        ...e.detail,
        conversation_id: app.globalData.customerChoose.conversation_id,
      },
    })
  },

  /**
   * @description: 点击QA查看更多
   */
  onQuestionMore(e) {
    this.setData({
      isQuestionOpen: true,
    })
  },

  /**
   * @description: 点击QA的tab
   */
  onQuestionTab(e) {
    const {
      index
    } = e.currentTarget.dataset
    this.setData({
      activeIndex: index
    })
  },

  /**
   * @description: 点击QAsubtab
   */
  onSubQuestionTab(e) {
    const {
      item
    } = e.currentTarget.dataset
    this.sendText({
      detail: item
    });
    this.setData({
      isQuestionOpen: false
    })
  },

  /**
   * @description: 关闭弹窗
   */
  closeModal() {
    this.setData({
      isQuestionOpen: false
    })
  },

  /**
   * @description: 筛选
   */
  onSubmit(e) {
    const customerChoose = app.globalData.customerChoose || {}
    const {
      loading,
      isBot
    } = this.data
    if (loading || !isBot) return
    this.handleLoading(true)
    customerApi.submitProductList({
      data: {
        ...e.detail,
        conversation_id: customerChoose.conversation_id,
        uid: customerChoose.uid,
      },
      success: (res) => {
        if (+res.code === 0) {
          this.handleSuccess();
        } else {
          this.handleLoading(false)
        }
      },
      fail: () => {
        this.handleLoading(false)
      }
    })
  },

  /**
   * @description: 查看历史消息
   */
  more() {
    if (!this.data.talkList[0]) return
    this.setData({
      beforeTime: this.data.talkList[0].send_time,
      afterTime: null,
    }, () => {
      this.showLoading()
      this.getList()
    })
  },

  /**
   * @description: 点击相册
   */
  showPic() {
    const that = this
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success(res) {
        // tempFilePath可以作为img标签的src属性显示图片
        const tempFilePaths = res.tempFilePaths[0]
        wx.uploadFile({
          url: upload, //仅为示例，非真实的接口地址
          filePath: tempFilePaths,
          name: 'file',
          success(res) {
            const data = JSON.parse(res.data)
            if (data.code * 1 === 0) {
              let url = data.data.url
              that.sendImageMessageUrl(url)
            }
          }
        })
      }
    })
  },

  sendImageMessageUrl(url) {
    const customerChoose = app.globalData.customerChoose || {}
    if (this.data.loading) return
    this.handleLoading(true)
    customerApi.sendImageMessageUrl({
      data: {
        friend_uid: customerChoose.friend_uid,
        friend_type: customerChoose.friend_type,
        conversation_id: customerChoose.conversation_id,
        image_url: url
      },
      success: (res) => {
        if (+res.code === 0) {
          this.handleSuccess();
        } else {
          this.handleLoading(false)
        }
      },
      fail: () => {
        this.handleLoading(false)
      }
    })
  },

  showImg(e) {
    let url = e.currentTarget.dataset.url
    wx.previewImage({
      urls: [url]
    })
  }
})